#import "LightSettingBarView.h"
#import "LightSettingModel.h"
#import <Masonry/Masonry.h>
#import <objc/runtime.h>
#import "CustomColorManager.h"
#import <RSColorPicker/RSColorPickerView.h>
#import "LightBarIconButton.h"

// 色块和加号尺寸、间距
#define COLOR_ITEM_SIZE 36
#define COLOR_ITEM_RADIUS 18
#define COLOR_ITEM_SPACING 12
#define COLOR_ITEM_BORDER_WIDTH 3
#define COLOR_ITEM_SELECTED_COLOR [UIColor whiteColor]
#define COLOR_ITEM_UNSELECTED_COLOR [UIColor clearColor]
#define BAR_BG_COLOR [UIColor colorWithWhite:0 alpha:0.92]
#define BAR_CORNER_RADIUS 32
#define BAR_SIDE_PADDING 15
#define BAR_GROUP_SPACING 14
#define TOP_BTN_FONT [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold]
#define TOP_BTN_SELECTED_COLOR [UIColor colorWithRed:1 green:0.85 blue:0.2 alpha:1]
#define TOP_BTN_NORMAL_COLOR [UIColor whiteColor]
#define SLIDER_HEIGHT 30
#define SLIDER_THUMB_SIZE 26
#define SLIDER_LABEL_FONT [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold]
#define SLIDER_LABEL_COLOR [UIColor colorWithRed:1 green:0.85 blue:0.2 alpha:1]

@interface LightSettingBarView () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIButton *liveBtn;
@property (nonatomic, strong) UIButton *mirrorBtn;
@property (nonatomic, strong) NSArray *timerBtns;
@property (nonatomic, strong) UISlider *zoomSlider;
@property (nonatomic, strong) UILabel *zoomLabel;
@property (nonatomic, strong) UISlider *brightnessSlider;
@property (nonatomic, strong) UILabel *brightnessLabel;
@property (nonatomic, strong) UICollectionView *colorCollectionView;
@property (nonatomic, strong) NSArray<UIColor *> *colorArray;
@property (nonatomic, strong) UICollectionView *customColorCollectionView;
@property (nonatomic, strong) NSMutableArray<UIColor *> *customColors;
@property (nonatomic, strong) UIImageView *zoomLeftIcon;
@property (nonatomic, strong) UIImageView *zoomRightIcon;
@property (nonatomic, strong) UIImageView *brightnessLeftIcon;
@property (nonatomic, strong) UIImageView *brightnessRightIcon;
@property (nonatomic, strong) UIButton *addCustomColorBtn;

@end

@implementation LightSettingBarView

#pragma mark - 懒加载控件
- (UIView *)contentView {
    if (!_contentView) {
        _contentView = [[UIView alloc] init];
        _contentView.backgroundColor = [UIColor colorWithRed:0.07 green:0.07 blue:0.07 alpha:1.0];
        _contentView.layer.cornerRadius = 20;
        [self addSubview:_contentView];
        [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self);
            make.top.equalTo(self);
        }];
    }
    return _contentView;
}

- (UIButton *)liveBtn {
    if (!_liveBtn) {
        _liveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_liveBtn setTitle:@"Live" forState:UIControlStateNormal];
        [_liveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_liveBtn setTitleColor:[UIColor yellowColor] forState:UIControlStateSelected];
        _liveBtn.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
        [self.contentView addSubview:_liveBtn];
        // 建议在 reloadAll 或布局方法中设置约束
    }
    return _liveBtn;
}

- (UIButton *)mirrorBtn {
    if (!_mirrorBtn) {
        _mirrorBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_mirrorBtn setTitle:@"镜像" forState:UIControlStateNormal];
        [_mirrorBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_mirrorBtn setTitleColor:[UIColor yellowColor] forState:UIControlStateSelected];
        _mirrorBtn.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
        [self.contentView addSubview:_mirrorBtn];
    }
    return _mirrorBtn;
}

- (NSArray *)timerBtns {
    if (!_timerBtns) {
        NSMutableArray *arr = [NSMutableArray array];
        NSArray *timerTitles = @[@"关", @"3秒", @"7秒"];
        for (int i = 0; i < timerTitles.count; i++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [btn setTitle:timerTitles[i] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor yellowColor] forState:UIControlStateSelected];
            btn.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
            btn.tag = i;
            [self.contentView addSubview:btn];
            [arr addObject:btn];
        }
        _timerBtns = arr;
    }
    return _timerBtns;
}

- (UISlider *)zoomSlider {
    if (!_zoomSlider) {
        _zoomSlider = [[UISlider alloc] init];
        _zoomSlider.minimumValue = 1.0; // 前置摄像头通常不支持小于1.0的缩放
        _zoomSlider.maximumValue = 2.0;
        [_zoomSlider setThumbImage:[self sliderThumbImage] forState:UIControlStateNormal];
        _zoomSlider.minimumTrackTintColor = TOP_BTN_SELECTED_COLOR;
        _zoomSlider.maximumTrackTintColor = [UIColor colorWithWhite:0.3 alpha:1];
        [self.contentView addSubview:_zoomSlider];
    }
    return _zoomSlider;
}

- (UILabel *)zoomLabel {
    if (!_zoomLabel) {
        _zoomLabel = [[UILabel alloc] init];
        _zoomLabel.textColor = [UIColor whiteColor];
        _zoomLabel.font = [UIFont systemFontOfSize:14];
        [self.contentView addSubview:_zoomLabel];
    }
    return _zoomLabel;
}

- (UISlider *)brightnessSlider {
    if (!_brightnessSlider) {
        _brightnessSlider = [[UISlider alloc] init];
        _brightnessSlider.minimumValue = 0;
        _brightnessSlider.maximumValue = 100;
        [_brightnessSlider setThumbImage:[self sliderThumbImage] forState:UIControlStateNormal];
        _brightnessSlider.minimumTrackTintColor = TOP_BTN_SELECTED_COLOR;
        _brightnessSlider.maximumTrackTintColor = [UIColor colorWithWhite:0.3 alpha:1];
        [self.contentView addSubview:_brightnessSlider];
    }
    return _brightnessSlider;
}

- (UILabel *)brightnessLabel {
    if (!_brightnessLabel) {
        _brightnessLabel = [[UILabel alloc] init];
        _brightnessLabel.textColor = [UIColor whiteColor];
        _brightnessLabel.font = [UIFont systemFontOfSize:14];
        [self.contentView addSubview:_brightnessLabel];
    }
    return _brightnessLabel;
}

- (UICollectionView *)colorCollectionView {
    if (!_colorCollectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.itemSize = CGSizeMake(COLOR_ITEM_SIZE, COLOR_ITEM_SIZE);
        layout.minimumInteritemSpacing = 12;
        layout.minimumLineSpacing = 12;
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _colorCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _colorCollectionView.backgroundColor = [UIColor clearColor];
        _colorCollectionView.showsHorizontalScrollIndicator = NO;
        _colorCollectionView.scrollEnabled = YES;
        _colorCollectionView.delegate = self;
        _colorCollectionView.dataSource = self;
        [_colorCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"ColorCell"];
        [self.contentView addSubview:_colorCollectionView];
    }
    return _colorCollectionView;
}

- (NSArray<UIColor *> *)colorArray {
    if (!_colorArray) {
        _colorArray = @[
            [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0],
            [UIColor colorWithRed:1.0 green:0.89 blue:0.74 alpha:1.0],
            [UIColor colorWithRed:0.74 green:0.87 blue:1.0 alpha:1.0],
            [UIColor colorWithRed:1.0 green:0.74 blue:0.47 alpha:1.0],
            [UIColor colorWithRed:1.0 green:0.74 blue:0.87 alpha:1.0],
            [UIColor colorWithRed:0.78 green:0.74 blue:1.0 alpha:1.0],
            [UIColor colorWithRed:1.0 green:0.93 blue:0.53 alpha:1.0]
        ];
    }
    return _colorArray;
}

- (UICollectionView *)customColorCollectionView {
    if (!_customColorCollectionView) {
        UICollectionViewFlowLayout *customLayout = [[UICollectionViewFlowLayout alloc] init];
        customLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        customLayout.itemSize = CGSizeMake(COLOR_ITEM_SIZE, COLOR_ITEM_SIZE);
        customLayout.minimumInteritemSpacing = 12;
        customLayout.minimumLineSpacing = 12;
        customLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _customColorCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:customLayout];
        _customColorCollectionView.backgroundColor = [UIColor clearColor];
        _customColorCollectionView.showsHorizontalScrollIndicator = NO;
        _customColorCollectionView.scrollEnabled = YES;
        _customColorCollectionView.delegate = self;
        _customColorCollectionView.dataSource = self;
        [_customColorCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"CustomColorCell"];
        [self.contentView addSubview:_customColorCollectionView];
    }
    return _customColorCollectionView;
}

- (NSMutableArray<UIColor *> *)customColors {
    if (!_customColors) {
        _customColors = [NSMutableArray array];
    }
    return _customColors;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
        self.customColors = [NSMutableArray array];
        [self loadCustomColors]; // 加载本地自定义色块
        [self setupUI];
    }
    return self;
}

// 自定义icon视图
- (UIView *)magnifierIconWithSymbol:(NSString *)symbol {
    UIView *iconView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
    UIImageView *magnifier = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"magnifyingglass"]];
    magnifier.frame = iconView.bounds;
    magnifier.tintColor = [UIColor whiteColor];
    magnifier.contentMode = UIViewContentModeScaleAspectFit;
    [iconView addSubview:magnifier];
    UILabel *label = [[UILabel alloc] initWithFrame:iconView.bounds];
    label.text = symbol;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont boldSystemFontOfSize:16];
    label.textAlignment = NSTextAlignmentCenter;
    [iconView addSubview:label];
    return iconView;
}

- (void)setupUI {
    // contentView
    self.contentView = [[UIView alloc] init];
    self.contentView.backgroundColor = BAR_BG_COLOR;
    self.contentView.layer.cornerRadius = BAR_CORNER_RADIUS;
    self.contentView.layer.masksToBounds = YES;
    [self addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self);
        make.top.equalTo(self);
    }];
    NSLog(@"barView.userInteractionEnabled = %d", self.userInteractionEnabled);
    NSLog(@"contentView.userInteractionEnabled = %d", self.contentView.userInteractionEnabled);

    // 顶部功能按钮
    LightBarIconButton *liveBtn = [[LightBarIconButton alloc] init];
    [liveBtn setIcon:[UIImage systemImageNamed:@"livephoto"] title:@"Live"];
    liveBtn.tag = ButtonTagLive;
    NSLog(@"liveBtn.userInteractionEnabled = %d", liveBtn.userInteractionEnabled);
    
    LightBarIconButton *mirrorBtn = [[LightBarIconButton alloc] init];
    [mirrorBtn setIcon:[UIImage systemImageNamed:@"triangle.lefthalf.filled"] title:@"镜像"];
    mirrorBtn.tag = ButtonTagMirror;
    NSLog(@"mirrorBtn.userInteractionEnabled = %d", mirrorBtn.userInteractionEnabled);
    
    LightBarIconButton *timerOffBtn = [[LightBarIconButton alloc] init];
    [timerOffBtn setIcon:[UIImage systemImageNamed:@"timer"] title:@"关"];
    timerOffBtn.tag = ButtonTagTimerOff;
    
    LightBarIconButton *timer3Btn = [[LightBarIconButton alloc] init];
    [timer3Btn setIcon:[UIImage systemImageNamed:@"timer"] title:@"3秒"];
    timer3Btn.tag = ButtonTagTimer3s;
    
    LightBarIconButton *timer7Btn = [[LightBarIconButton alloc] init];
    [timer7Btn setIcon:[UIImage systemImageNamed:@"timer"] title:@"7秒"];
    timer7Btn.tag = ButtonTagTimer7s;
    NSLog(@"timerOffBtn.userInteractionEnabled = %d", timerOffBtn.userInteractionEnabled);
    NSLog(@"timer3Btn.userInteractionEnabled = %d", timer3Btn.userInteractionEnabled);
    NSLog(@"timer7Btn.userInteractionEnabled = %d", timer7Btn.userInteractionEnabled);
    self.liveBtn = liveBtn;
    self.mirrorBtn = mirrorBtn;
    self.timerBtns = @[timerOffBtn, timer3Btn, timer7Btn];
    NSArray *topBtns = @[liveBtn, mirrorBtn, timerOffBtn, timer3Btn, timer7Btn];
    UIStackView *topStack = [[UIStackView alloc] initWithArrangedSubviews:topBtns];
    topStack.axis = UILayoutConstraintAxisHorizontal;
    topStack.distribution = UIStackViewDistributionEqualCentering;
    topStack.alignment = UIStackViewAlignmentCenter;
    topStack.spacing = 10;
    [self.contentView addSubview:topStack];
    // 1. 顶部功能按钮
    [topStack mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(30);
        make.right.equalTo(self.contentView).offset(-30);
        make.top.equalTo(self.contentView).offset(18);
        make.height.mas_equalTo(56);
    }];
    NSLog(@"topStack.userInteractionEnabled = %d", topStack.userInteractionEnabled);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"liveBtn.frame = %@", NSStringFromCGRect(self.liveBtn.frame));
        NSLog(@"mirrorBtn.frame = %@", NSStringFromCGRect(self.mirrorBtn.frame));
        NSLog(@"timerOffBtn.frame = %@", NSStringFromCGRect(timerOffBtn.frame));
        NSLog(@"timer3Btn.frame = %@", NSStringFromCGRect(timer3Btn.frame));
        NSLog(@"timer7Btn.frame = %@", NSStringFromCGRect(timer7Btn.frame));
        NSLog(@"topStack.frame = %@", NSStringFromCGRect(topStack.frame));
        NSLog(@"contentView.frame = %@", NSStringFromCGRect(self.contentView.frame));
        NSLog(@"barView.frame = %@", NSStringFromCGRect(self.frame));
    });
    // 2. 缩放
    self.zoomLeftIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"zoomIn"]];
    self.zoomLeftIcon.tintColor = [UIColor whiteColor];
    [self.contentView addSubview:self.zoomLeftIcon];
    self.zoomRightIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"zoomOut"]];
    self.zoomRightIcon.tintColor = [UIColor whiteColor];
    [self.contentView addSubview:self.zoomRightIcon];
    self.zoomLabel = [[UILabel alloc] init];
    self.zoomLabel.textColor = SLIDER_LABEL_COLOR;
    self.zoomLabel.font = SLIDER_LABEL_FONT;
    [self.contentView addSubview:self.zoomLabel];
    [self.zoomLeftIcon mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(BAR_SIDE_PADDING);
        make.top.equalTo(topStack.mas_bottom).offset(24);
        make.width.height.mas_equalTo(22);
    }];
    [self.zoomSlider mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.zoomLeftIcon.mas_right).offset(8);
        make.centerY.equalTo(self.zoomLeftIcon);
        make.right.equalTo(self.zoomRightIcon.mas_left).offset(-8);
        make.height.mas_equalTo(SLIDER_HEIGHT);
    }];
    [self.zoomRightIcon mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.zoomLeftIcon);
        make.width.height.mas_equalTo(22);
        make.right.equalTo(self.zoomLabel.mas_left).offset(-8);
    }];
    [self.zoomLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.contentView).offset(-BAR_SIDE_PADDING);
        make.centerY.equalTo(self.zoomLeftIcon);
        make.width.mas_equalTo(44);
    }];
    // 3. 亮度
    self.brightnessLeftIcon = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"sun.max"]];
    self.brightnessLeftIcon.tintColor = [UIColor whiteColor];
    [self.contentView addSubview:self.brightnessLeftIcon];
  
    self.brightnessRightIcon = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"sun.max.fill"]];
    self.brightnessRightIcon.tintColor = [UIColor whiteColor];
    [self.contentView addSubview:self.brightnessRightIcon];
    self.brightnessLabel = [[UILabel alloc] init];
    self.brightnessLabel.textColor = SLIDER_LABEL_COLOR;
    self.brightnessLabel.font = SLIDER_LABEL_FONT;
    [self.contentView addSubview:self.brightnessLabel];
    [self.brightnessLeftIcon mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(BAR_SIDE_PADDING);
        make.top.equalTo(self.zoomLeftIcon.mas_bottom).offset(24);
        make.width.height.mas_equalTo(22);
    }];
    [self.brightnessSlider mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.brightnessLeftIcon.mas_right).offset(8);
        make.centerY.equalTo(self.brightnessLeftIcon);
        make.right.equalTo(self.brightnessRightIcon.mas_left).offset(-8);
        make.height.mas_equalTo(SLIDER_HEIGHT);
    }];
    [self.brightnessRightIcon mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.brightnessLeftIcon);
        make.width.height.mas_equalTo(22);
        make.right.equalTo(self.brightnessLabel.mas_left).offset(-8);
    }];
    [self.brightnessLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.contentView).offset(-BAR_SIDE_PADDING);
        make.centerY.equalTo(self.brightnessLeftIcon);
        make.width.mas_equalTo(44);
    }];
    // 4. 默认色块
    [self.colorCollectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.contentView).inset(40);
        make.top.equalTo(self.brightnessLeftIcon.mas_bottom).offset(24);
        make.height.mas_equalTo(COLOR_ITEM_SIZE);
    }];
    // 5. 自定义色块
    self.addCustomColorBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.addCustomColorBtn setTitle:@"+" forState:UIControlStateNormal];
    [self.addCustomColorBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.addCustomColorBtn.titleLabel.font = [UIFont boldSystemFontOfSize:28];
    self.addCustomColorBtn.backgroundColor = [UIColor whiteColor];
    self.addCustomColorBtn.layer.cornerRadius = COLOR_ITEM_RADIUS;
    self.addCustomColorBtn.layer.masksToBounds = YES;
    [self.addCustomColorBtn addTarget:self action:@selector(addCustomColorBtnTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.addCustomColorBtn];
    [self.addCustomColorBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(40);
        make.top.equalTo(self.colorCollectionView.mas_bottom).offset(24);
        make.size.mas_equalTo(CGSizeMake(COLOR_ITEM_SIZE, COLOR_ITEM_SIZE));
        make.bottom.equalTo(self.contentView.mas_bottom).offset(-[self safeAreaBottom]-24);
    }];
    [self.customColorCollectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.addCustomColorBtn.mas_right).offset(COLOR_ITEM_SPACING);
        make.right.equalTo(self.contentView).offset(-40);
        make.top.equalTo(self.colorCollectionView.mas_bottom).offset(24);
        make.height.mas_equalTo(COLOR_ITEM_SIZE);
        make.bottom.equalTo(self.contentView.mas_bottom).offset(-[self safeAreaBottom]-24);
    }];



    // 事件绑定
    [self.liveBtn addTarget:self action:@selector(liveBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.mirrorBtn addTarget:self action:@selector(mirrorBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.timerBtns enumerateObjectsUsingBlock:^(LightBarIconButton *btn, NSUInteger idx, BOOL *stop) {
        [btn addTarget:self action:@selector(timerBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    }];
    [self.zoomSlider addTarget:self action:@selector(zoomSliderChanged:) forControlEvents:UIControlEventValueChanged];
    [self.brightnessSlider addTarget:self action:@selector(brightnessSliderChanged:) forControlEvents:UIControlEventValueChanged];
    // 初始化label内容
    self.zoomLabel.text = [NSString stringWithFormat:@"%.1fx", self.zoomSlider.value];
    self.brightnessLabel.text = [NSString stringWithFormat:@"%.0f%%", self.brightnessSlider.value];
}

- (UIButton *)createTopButtonWithTitle:(NSString *)title {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:TOP_BTN_NORMAL_COLOR forState:UIControlStateNormal];
    [btn setTitleColor:TOP_BTN_SELECTED_COLOR forState:UIControlStateSelected];
    btn.titleLabel.font = TOP_BTN_FONT;
    return btn;
}

- (UIImage *)sliderThumbImage {
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(SLIDER_THUMB_SIZE, SLIDER_THUMB_SIZE), NO, 0);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(ctx, [UIColor whiteColor].CGColor);
    CGContextFillEllipseInRect(ctx, CGRectMake(0, 0, SLIDER_THUMB_SIZE, SLIDER_THUMB_SIZE));
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

- (CGFloat)safeAreaBottom {
    if (@available(iOS 11.0, *)) {
        UIWindow *window = UIApplication.sharedApplication.keyWindow;
        return window.safeAreaInsets.bottom;
    }
    return 0;
}

#pragma mark - UICollectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.customColorCollectionView) {
        return self.customColors.count; // 只显示自定义色块
    }
    return self.colorArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.customColorCollectionView) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CustomColorCell" forIndexPath:indexPath];
        for (UIView *sub in cell.contentView.subviews) [sub removeFromSuperview];
        UIView *circle = [[UIView alloc] initWithFrame:cell.contentView.bounds];
        circle.backgroundColor = self.customColors[indexPath.item];
        circle.layer.cornerRadius = COLOR_ITEM_RADIUS;
        circle.layer.masksToBounds = YES;
        BOOL selected = [self isColor:self.customColors[indexPath.item] equalToColor:self.settingModel.selectedColor];
        NSLog(@"自定义色块 %ld: selected=%d, settingModel.selectedColor=%@, currentColor=%@", (long)indexPath.item, selected, self.settingModel.selectedColor, self.customColors[indexPath.item]);
        if (selected) {
            // 外圈白色描边
            circle.layer.borderWidth = COLOR_ITEM_BORDER_WIDTH;
            circle.layer.borderColor = COLOR_ITEM_SELECTED_COLOR.CGColor;
            // 内部黑色半透明圆环，紧贴白色描边
            CGFloat ringBorderWidth = 1.2;
            CGFloat ringDiameter = COLOR_ITEM_SIZE - 2 * COLOR_ITEM_BORDER_WIDTH;
            UIView *ring = [[UIView alloc] initWithFrame:CGRectMake(COLOR_ITEM_BORDER_WIDTH, COLOR_ITEM_BORDER_WIDTH, ringDiameter, ringDiameter)];
            ring.backgroundColor = [UIColor clearColor];
            ring.layer.cornerRadius = ringDiameter / 2.0;
            ring.layer.masksToBounds = YES;
            ring.layer.borderWidth = ringBorderWidth;
            ring.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5].CGColor;
            [circle addSubview:ring];
        } else {
            circle.layer.borderWidth = 0;
            circle.layer.borderColor = COLOR_ITEM_UNSELECTED_COLOR.CGColor;
        }
        [cell.contentView addSubview:circle];
        // 删除按钮
        UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        if (@available(iOS 13.0, *)) {
            UIImage *img = [UIImage systemImageNamed:@"xmark.circle.fill"];
            [deleteBtn setImage:img forState:UIControlStateNormal];
        } else {
            [deleteBtn setTitle:@"×" forState:UIControlStateNormal];
            [deleteBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        }
        deleteBtn.tintColor = [UIColor redColor];
        deleteBtn.frame = CGRectMake(COLOR_ITEM_SIZE-18, -6, 24, 24);
        deleteBtn.hidden = YES;
        deleteBtn.tag = 10086;
        [deleteBtn addTarget:self action:@selector(deleteCustomColorBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
        [circle addSubview:deleteBtn];
        // 长按手势
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleCustomColorLongPress:)];
        [cell addGestureRecognizer:longPress];
        cell.tag = indexPath.item;
        return cell;
    }
    // 默认色块cell
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ColorCell" forIndexPath:indexPath];
    for (UIView *sub in cell.contentView.subviews) [sub removeFromSuperview];
    UIView *circle = [[UIView alloc] initWithFrame:cell.contentView.bounds];
    circle.backgroundColor = self.colorArray[indexPath.item];
    circle.layer.cornerRadius = COLOR_ITEM_RADIUS;
    circle.layer.masksToBounds = YES;
    BOOL selected = [self isColor:self.colorArray[indexPath.item] equalToColor:self.settingModel.selectedColor];
    NSLog(@"默认色块 %ld: selected=%d, settingModel.selectedColor=%@, currentColor=%@", (long)indexPath.item, selected, self.settingModel.selectedColor, self.colorArray[indexPath.item]);
    if (selected) {
        // 外圈白色描边
        circle.layer.borderWidth = COLOR_ITEM_BORDER_WIDTH;
        circle.layer.borderColor = COLOR_ITEM_SELECTED_COLOR.CGColor;
        // 内部黑色半透明圆环，紧贴白色描边
        CGFloat ringBorderWidth = 1.2;
        CGFloat ringDiameter = COLOR_ITEM_SIZE - 2 * COLOR_ITEM_BORDER_WIDTH;
        UIView *ring = [[UIView alloc] initWithFrame:CGRectMake(COLOR_ITEM_BORDER_WIDTH, COLOR_ITEM_BORDER_WIDTH, ringDiameter, ringDiameter)];
        ring.backgroundColor = [UIColor clearColor];
        ring.layer.cornerRadius = ringDiameter / 2.0;
        ring.layer.masksToBounds = YES;
        ring.layer.borderWidth = ringBorderWidth;
        ring.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5].CGColor;
        [circle addSubview:ring];
    } else {
        circle.layer.borderWidth = 0;
        circle.layer.borderColor = COLOR_ITEM_UNSELECTED_COLOR.CGColor;
    }
    [cell.contentView addSubview:circle];
    return cell;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(COLOR_ITEM_SIZE, COLOR_ITEM_SIZE);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.colorCollectionView) {
        // 选择默认颜色
        UIColor *selectedColor = self.colorArray[indexPath.item];
        NSLog(@"点击默认色块 %ld: 设置selectedColor=%@", (long)indexPath.item, selectedColor);
        self.settingModel.selectedColor = selectedColor;
        self.settingModel.currentSettingType = ButtonTagColor;
        if (self.onSettingChanged) self.onSettingChanged(self.settingModel);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.colorCollectionView reloadData];
        });
    } else if (collectionView == self.customColorCollectionView) {
        // 选择自定义颜色
        UIColor *selectedColor = self.customColors[indexPath.item];
        self.settingModel.selectedColor = selectedColor;
        self.settingModel.currentSettingType = ButtonTagColor;
        if (self.onSettingChanged) self.onSettingChanged(self.settingModel);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.customColorCollectionView reloadData];
        });
    }
}

- (void)setSettingModel:(LightSettingModel *)settingModel {
    _settingModel = settingModel;
    [self reloadAll];
}

- (void)reloadAll {
    self.liveBtn.selected = self.settingModel.liveEnabled;
    self.mirrorBtn.selected = self.settingModel.mirrorEnabled;
    [self.timerBtns enumerateObjectsUsingBlock:^(LightBarIconButton *btn, NSUInteger idx, BOOL *stop) {
        btn.selected = (idx == self.settingModel.timerType);
    }];
    
    // 回显放大滑块
    self.zoomSlider.value = self.settingModel.zoomValue;
    self.zoomLabel.text = [NSString stringWithFormat:@"%.1fx", self.settingModel.zoomValue];
    
    // 回显亮度滑块
    self.brightnessSlider.value = self.settingModel.brightness;
    self.brightnessLabel.text = [NSString stringWithFormat:@"%ld%%", (long)self.settingModel.brightness];
    
    // 刷新所有UI控件的状态，回显设置项
    // 可调用 reloadCustomColors 等方法
}



- (void)liveBtnTapped:(LightBarIconButton *)sender {
    sender.selected = !sender.selected;
    self.settingModel.liveEnabled = sender.selected;
    self.settingModel.currentSettingType = sender.tag;
    NSLog(@"LIVE按钮点击: %@", sender.selected ? @"开启" : @"关闭");
    if (self.onSettingChanged) self.onSettingChanged(self.settingModel);
}

- (void)mirrorBtnTapped:(LightBarIconButton *)sender {
    sender.selected = !sender.selected;
    self.settingModel.mirrorEnabled = sender.selected;
    self.settingModel.currentSettingType = sender.tag;
    if (self.onSettingChanged) self.onSettingChanged(self.settingModel);
}

- (void)timerBtnTapped:(LightBarIconButton *)sender {
    [self.timerBtns enumerateObjectsUsingBlock:^(LightBarIconButton *btn, NSUInteger idx, BOOL *stop) {
        btn.selected = (btn == sender);
        if (btn == sender) {
            self.settingModel.timerType = idx;
        }
    }];
    self.settingModel.currentSettingType = sender.tag;
    if (self.onSettingChanged) self.onSettingChanged(self.settingModel);
}

- (void)zoomSliderChanged:(UISlider *)slider {
    self.zoomLabel.text = [NSString stringWithFormat:@"%.1fx", slider.value];
    self.settingModel.zoomValue = slider.value;
    self.settingModel.currentSettingType = ButtonTagZoom;
    if (self.onSettingChanged) self.onSettingChanged(self.settingModel);
}

- (void)brightnessSliderChanged:(UISlider *)slider {
    self.brightnessLabel.text = [NSString stringWithFormat:@"%.0f%%", slider.value];
    self.settingModel.brightness = (NSInteger)slider.value;
    self.settingModel.currentSettingType = ButtonTagBrightness;
    if (self.onSettingChanged) self.onSettingChanged(self.settingModel);
}

#pragma mark - 自定义色块添加
- (void)addCustomColorBtnTapped {
    // 获取bar在window中的frame
    UIWindow *keyWindow = UIApplication.sharedApplication.keyWindow;
    CGRect barFrame = [self convertRect:self.bounds toView:keyWindow];
    // 创建弹窗父视图，frame与bar一致
    UIView *bgView = [[UIView alloc] initWithFrame:barFrame];
    bgView.backgroundColor = [UIColor clearColor]; // 彻底透明，去除阴影
    bgView.userInteractionEnabled = YES;
    [keyWindow addSubview:bgView];

    // 添加点击手势到bgView
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleColorPickerBgTap:)];
    [bgView addGestureRecognizer:tap];

    // 弹窗内容视图，frame为(0,0,width,height)
    UIView *dialog = [[UIView alloc] initWithFrame:CGRectMake(0, 0, bgView.bounds.size.width, bgView.bounds.size.height)];
    dialog.backgroundColor = BAR_BG_COLOR;
    dialog.layer.cornerRadius = BAR_CORNER_RADIUS;
    dialog.layer.masksToBounds = YES;
    [bgView addSubview:dialog];

    // 按钮高度
    CGFloat btnH = 40;
    CGFloat btnW = 60;
    CGFloat btnTop = 12;
    // 取消按钮
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:20 weight:UIFontWeightRegular];
    cancelBtn.frame = CGRectMake(24, btnTop, btnW, btnH);
    [dialog addSubview:cancelBtn];
    // 保存按钮
    UIButton *okBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [okBtn setTitle:@"保存" forState:UIControlStateNormal];
    [okBtn setTitleColor:[UIColor colorWithRed:0.2 green:0.6 blue:1 alpha:1] forState:UIControlStateNormal];
    okBtn.titleLabel.font = [UIFont systemFontOfSize:20 weight:UIFontWeightSemibold];
    okBtn.frame = CGRectMake(dialog.bounds.size.width-24-btnW, btnTop, btnW, btnH);
    [dialog addSubview:okBtn];

    // 色盘
    CGFloat pickerSize = MIN(dialog.bounds.size.width, dialog.bounds.size.height) - 48 - btnH - 24;
    CGFloat pickerY = btnTop + btnH + 12;
    RSColorPickerView *colorPicker = [[RSColorPickerView alloc] initWithFrame:CGRectMake((dialog.bounds.size.width-pickerSize)/2, pickerY, pickerSize, pickerSize)];
    colorPicker.cropToCircle = YES;
    colorPicker.showLoupe = YES;
    [dialog addSubview:colorPicker];

    // 事件
    [cancelBtn addTarget:self action:@selector(dismissCustomColorDialog:) forControlEvents:UIControlEventTouchUpInside];
    [okBtn addTarget:self action:@selector(confirmCustomColorDialog:) forControlEvents:UIControlEventTouchUpInside];
    objc_setAssociatedObject(okBtn, "colorPicker", colorPicker, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(okBtn, "bgView", bgView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)dismissCustomColorDialog:(UIButton *)sender {
    UIView *bgView = sender.superview.superview;
    [bgView removeFromSuperview];
}

- (void)confirmCustomColorDialog:(UIButton *)sender {
    RSColorPickerView *colorPicker = objc_getAssociatedObject(sender, "colorPicker");
    UIView *bgView = objc_getAssociatedObject(sender, "bgView");
    UIColor *color = [colorPicker colorAtPoint:colorPicker.selection];
    if (color) {
        [self.customColors addObject:color];
        [self.customColorCollectionView reloadData];
        [self saveCustomColors]; // 保存到本地
    }
    [bgView removeFromSuperview];
}

#pragma mark - 自定义色块持久化
- (void)saveCustomColors {
    NSMutableArray *colorStrings = [NSMutableArray array];
    for (UIColor *color in self.customColors) {
        CGFloat r, g, b, a;
        if ([color getRed:&r green:&g blue:&b alpha:&a]) {
            NSString *rgba = [NSString stringWithFormat:@"%0.4f,%0.4f,%0.4f,%0.4f", r, g, b, a];
            [colorStrings addObject:rgba];
        }
    }
    [[NSUserDefaults standardUserDefaults] setObject:colorStrings forKey:@"CustomColors"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)loadCustomColors {
    NSArray *colorStrings = [[NSUserDefaults standardUserDefaults] objectForKey:@"CustomColors"];
    [self.customColors removeAllObjects];
    for (NSString *rgba in colorStrings) {
        NSArray *comps = [rgba componentsSeparatedByString:@","];
        if (comps.count == 4) {
            UIColor *color = [UIColor colorWithRed:[comps[0] floatValue]
                                             green:[comps[1] floatValue]
                                              blue:[comps[2] floatValue]
                                             alpha:[comps[3] floatValue]];
            [self.customColors addObject:color];
        }
    }
}

// 其余按钮事件、slider事件、色盘弹窗、颜色持久化等逻辑与原Controller一致，略

// 准确的颜色比较方法
- (BOOL)isColor:(UIColor *)color1 equalToColor:(UIColor *)color2 {
    if (!color1 || !color2) {
        return NO;
    }
    
    CGFloat r1, g1, b1, a1, r2, g2, b2, a2;
    [color1 getRed:&r1 green:&g1 blue:&b1 alpha:&a1];
    [color2 getRed:&r2 green:&g2 blue:&b2 alpha:&a2];
    
    // 使用较小的容差值进行比较
    CGFloat tolerance = 0.01;
    return (fabs(r1 - r2) < tolerance &&
            fabs(g1 - g2) < tolerance &&
            fabs(b1 - b2) < tolerance &&
            fabs(a1 - a2) < tolerance);
}

// 长按显示删除按钮，2秒后自动隐藏
- (void)handleCustomColorLongPress:(UILongPressGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
        UICollectionViewCell *cell = (UICollectionViewCell *)gesture.view;
        NSInteger idx = cell.tag;
        if (idx >= 0 && idx < self.customColors.count) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"删除自定义色块" message:@"确定要删除这个自定义色块吗？" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
            [alert addAction:[UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                UIColor *deletedColor = self.customColors[idx];
                [self.customColors removeObjectAtIndex:idx];
                [self saveCustomColors];
                // 如果删除的是选中色块，恢复为默认色
                if ([self isColor:deletedColor equalToColor:self.settingModel.selectedColor]) {
                    self.settingModel.selectedColor = self.colorArray[0];
                    if (self.onSettingChanged) self.onSettingChanged(self.settingModel);
                }
                [self.customColorCollectionView reloadData];
            }]];
            UIWindow *keyWindow = UIApplication.sharedApplication.keyWindow;
            UIViewController *rootVC = keyWindow.rootViewController;
            while (rootVC.presentedViewController) rootVC = rootVC.presentedViewController;
            [rootVC presentViewController:alert animated:YES completion:nil];
        }
    }
}
// 删除按钮事件可保留但不再需要弹出按钮

- (void)handleColorPickerBgTap:(UITapGestureRecognizer *)tap {
    UIView *bgView = tap.view;
    CGPoint point = [tap locationInView:bgView];
    UIView *dialog = [bgView.subviews firstObject];
    if (!CGRectContainsPoint(dialog.frame, point)) {
        [bgView removeFromSuperview];
    }
}

@end 
